<template>
    <div class="params-contianer">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
      <!--警告提示的文案  -->
        <el-alert title="注意：只允许选择三级分类选项！非三级分类选项选择无效！" type="warning" :closable="false" show-icon>
          </el-alert>
        <!-- 选择商品分类 -->
        <el-row>
            <el-col ><span>选择商品分类：</span> 
            <el-cascader  v-model="selectedKeys" :options="cateList"  expand-trigger="hover"
                        :props="cateProps " @change="CateChanged" clearable ></el-cascader>
           </el-col>
             
        </el-row>
        <!-- 参数列表 -->
        <el-tabs type="border-card" v-model="activeName" @tab-click="tabClick">
            <!-- 添加动态参数面板 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled=' isBtnDisabled' @click="showAddParamsDialog">添加参数</el-button>
                <!-- 表格 -->
                <el-table  :data="manyTableData"  border  style="width: 100%">
                    <!-- 展开航 -->
                      <el-table-column type="expand">
                        <tempalte slot-scope="scope">
                         <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"  closable>{{item}}</el-tag>
                         <!-- 可编辑tag -->
                         <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                            >
                         </el-input>
                         <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                     </tempalte> 
                     </el-table-column>
                    <el-table-column type="index">  </el-table-column>

                    <el-table-column  prop="attr_id"  label="参数ID"  width="180">
                    </el-table-column>

                    <el-table-column  prop="attr_name"  label="参数名称"  width="180">
                    </el-table-column>

                    <el-table-column    label="操作"  width="180">
                        <template slot-scope="scope">
                           <el-button type="primary" icon="el-icon-setting"size="mini" @click="showEditParams(scope.row.attr_id)">修改</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>

                </el-table> 
            </el-tab-pane>

            <!-- 添加静态属性面板 -->
            <el-tab-pane label="静态属性" name="only">
                  <el-button type="primary" :disabled=" isBtnDisabled" @click="showAddParamsDialog">添加属性</el-button>
                   <!-- 表格 -->
                <el-table  :data="onlyTableData"  border  style="width: 100%">
                    <!-- 展开行 -->
                     <el-table-column type="expand">
                          <tempalte slot-scope="scope">
                         <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                     </tempalte>
                 </el-table-column>
                    
                     <el-table-column type="index"> </el-table-column>

                    <el-table-column  prop="attr_id"  label="参数ID"  width="180">
                    </el-table-column>

                    <el-table-column  prop="attr_name"  label="参数名称"  width="180">
                    </el-table-column>

                    <el-table-column    label="操作"  width="180">
                        <template slot-scope="scope">
                         
                           <el-button type="primary" icon="el-icon-setting"size="mini" @click="showEditParams(scope.row.attr_id)">修改</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>

                </el-table> 
            </el-tab-pane>
        </el-tabs>

            <!-- 添加参数对话框 -->
            <el-dialog :title="'添加'+titleText" :visible.sync="paramsVisible" width="50%" @close="resetAddParamsDialog" >
                <!--  表单-->
                    <el-form :model="AddParamsForm" :rules="paramsRules" ref="AddParamsFormRef" label-width="120px" class="demo-ruleForm">
                        <el-form-item :label="titleText+'名称'" prop="attr_name">
                            <el-input v-model="AddParamsForm.attr_name" clearable ></el-input>
                        </el-form-item>
                    </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="paramsVisible = false">取 消</el-button>
                    <el-button type="primary" @click="AddParams">确 定</el-button>
                </span>
              </el-dialog>
            <!-- 修改参数对话框 -->
            <el-dialog :title="'修改'+titleText" :visible.sync="editparamsVisible" width="50%" @close="resetParamsEditDialog" >
                <!--  表单-->
                    <el-form :model="editParamsForm" :rules="paramsRules" ref="editParamsFormRef" label-width="120px" class="demo-ruleForm">
                        <el-form-item :label="titleText+'名称'" prop="attr_name">
                            <el-input v-model="editParamsForm.attr_name" clearable ></el-input>
                        </el-form-item>
                    </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editparamsVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editParams">确 定</el-button>
                </span>
              </el-dialog>

        </div>
</template>

<script>
export default {
    data(){
        return{
            selectedKeys:[],
            cateList:{},
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            activeName:'many',
            manyTableData:[ ],
            onlyTableData:[],
            paramsVisible :false,
            editparamsVisible:false,
            AddParamsForm:{
                attr_name:''
            },
            editParamsForm:{
                attr_name:''
            },
            paramsRules:{
                attr_name:[
                     { required: true, message: '请输入活动名称', trigger: 'blur' },
                     { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created(){
            this.getCateList();
    },
    computed:{
        isBtnDisabled(){
            if(this.selectedKeys.length !== 3){
                return true
            }
            return false
        },
        cateId(){
                if(this.activeName == 'many'){

                    return  this.manyTableData[0].cat_id;
                }else{
                    return  this.onlyTableData[0].cat_id;
                }
        },

        titleText(){
            if(this.activeName == 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        },
    },
    methods:{
         async getCateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status !== 200 ) return this.$Message.error('分类列表数据获取失败！')
                this.cateList = res.data
                
        },
        CateChanged(){
            this.getParamsList()
        },
        //tab页签点击事件
        tabClick(){
            this.getParamsList();
            
        },
       
       async getParamsList(){
           const {data:res} = await this.$http.get(`categories/${this.selectedKeys[2]}/attributes`,{
               params:{sel:this.activeName}
           })
           if(res.meta.status !== 200) return this.$Message.error('获取失败')
           this.$Message.success('获取成功')
                    res.data.forEach( item => {
                        //  item.attr_vals !=='' ? item.attr_vals = this.aperture(8, item.attr_vals):[]
            // item.inputVisible =false;
            // item.inputValue= ''
            item.attr_vals !=='' ? item.attr_vals =  item.attr_vals.split(" "):[];
            item.inputVisible =false;
            item.inputValue= ''
                })
           if(this.activeName == 'many'){
               this.manyTableData = res.data;
           }else{

               this.onlyTableData = res.data
           }
        
        },
        showAddParamsDialog(){
            this.paramsVisible = true;
        },
        // 关闭重置对话框
        resetAddParamsDialog(){
          this.$refs.AddParamsFormRef.resetFields();
        },
        AddParams(){
           this.$refs.AddParamsFormRef.validate(async valid =>{
               if(!valid)  return 
                if(!this.cateId) return this.$Message.info('所选的分类ID为空')
            const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.AddParamsForm.attr_name,
                    attr_sel:this.activeName,
            })
            if(res.meta.status !== 201) return this.$Message.error('添加参数失败')
              this.paramsVisible = false;
              this.$Message.success('添加参数成功')
               this.getParamsList();
           })
          
        },
        // 修改

        async showEditParams(attr_id){
                
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{
                    params:{
                        // attr_name:attr_name,
                        attr_sel:this.activeName
                    }
                })
                if(res.meta.status !== 200) return this.$Message.error('获取参数失败')
                this.editParamsForm = res.data;
                this.editparamsVisible = true;

        },
        resetParamsEditDialog(){
            this.$refs.editParamsFormRef.resetFields();
            // this.editParamsForm ={}
        },
        editParams(){
             this.editparamsVisible = false;
             this.$refs.editParamsFormRef.validate(async valid =>{
                 if(!valid) return 
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/ ${this.editParamsForm.attr_id}`,
                 this.editParamsForm)
                 if(res.meta.status !== 200 ) return   this.$Message.error('更新参数失败')
                  this.$Message.success('更新参数成功')
                  this.getParamsList();
             })
           

        },
        deleteParams(attr_id){
            
            this.$confirm('此操作将永久删除参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( async () => {
                const {data:res} =  await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
                
                if(res.meta.status !==200) return this.$message.error('权限删除失败')
                this.$message.success('权限删除成功');
                 this.getParamsList();
                }).catch(() => {
                    this.$message({
                    type: 'info',
                    message: '已取消权限删除操作'
                });          
            });
        },
        // 可编辑tag事件keyup触发
        async handleInputConfirm(rowinfo){
            if(rowinfo.inputValue.trim().length == 0){
                rowinfo.inputValue =''
                rowinfo.inputVisible =false
                return
            }else{
        
                 rowinfo.inputValue =''
                rowinfo.inputVisible = false;
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${rowinfo.attr_id}`,{
                    attr_name:rowinfo.attr_name,
                    attr_sel:rowinfo.attr_sel,
                    attr_vals: rowinfo.attr_vals.join(' ')
                });
                if(res.meta.status !== 200) return this.$Message.error('参数可选项更新失败')
                this.getParamsList()
                this.$Message.success('参数可选项更新成功')
            }

        },
           // 可编辑tag事件blur触发
      
        showInput(rowinfo){
            rowinfo.inputVisible = true;
            // $nextTick当页面重新渲染后才会回调方法
            this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
        },
          aperture(n, arr){
             (Array.isArray(arr) ? arr : [arr]);
              return (n, arr) => n > arr.length ?
               [] :arr.slice(n - 1).map((v, i) => arr.slice(i, i + n))
          }
        
    }
}
</script>

<style lang="less" scoped>
.el-breadcrumb,.el-alert,.el-row{
    margin-bottom:15px;
}
.el-table{
     margin-top:15px;
}
.el-tag{
    margin:5px 10px;
}
.input-new-tag{
    width: 120px;

}
</style>